package com.zlyx.easy.api.web;

import java.util.List;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zlyx.easy.api.ApiManager;
import com.zlyx.easy.api.config.ApiConfigurer;
import com.zlyx.easy.api.json.Json;
import com.zlyx.easy.api.reader.ApiReader;
import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.utils.HttpUtils.HttpResponse;
import com.zlyx.easy.core.utils.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.models.Swagger;

@Api(hidden = true)
@Controller
@RequestMapping("method-api")
public class MethodApiController {

	public static final String DEFAULT_URL = "/api-docs";
	private static final String HAL_MEDIA_TYPE = "application/hal+json";

	@RequestMapping(value = DEFAULT_URL, method = RequestMethod.GET, produces = { "application/json; charset=utf-8",
			HAL_MEDIA_TYPE })
	@ResponseBody
	public ResponseEntity<Json> getApiList(String group) {
		try {
			if (ApiConfigurer.getApiProperties().isDisable()) {
				return new ResponseEntity<Json>(HttpStatus.BAD_REQUEST);
			}
			String res = ApiManager.getSwagger(group);
			Map<Class<?>, Object> interfaceMapRef = ApiManager.interfaceMapRef(group);
			if (StringUtils.isEmpty(res) && interfaceMapRef != null) {
				Swagger swagger = ApiConfigurer.getSwagger();
				if (null != interfaceMapRef) {
					ApiReader.read(interfaceMapRef, swagger);
				}
				res = ApiManager.registerSwagger(group, swagger);
			}
			return new ResponseEntity<Json>(new Json(res), HttpStatus.OK);
		} catch (Exception e) {
			Logger.err(e);
			return new ResponseEntity<Json>(new Json(HttpResponse.failure(e).toString()),
					HttpStatus.EXPECTATION_FAILED);
		}
	}

	@ResponseBody
	@RequestMapping("/apis/get")
	public Map<String, List<String>> getGroupNames() {
		return ApiManager.getGroupNames();
	}

	@GetMapping
	public String api() {
		return "redirect:apis.html";
	}
}
